<template>
  <div class="app-container">
    <wise-crud ref="wise-crud" :urls="urls" :fields="fields" :handle="handle" :filters="filters">
      <!--      <template v-slot:handle="slotProps">-->
      <!--        <el-button v-if="slotProps.row.showStates === 0" type="primary" size="small" round @click.native.prevent="startHandle(slotProps.row)">大屏展示</el-button>-->
      <!--        <el-button v-if="slotProps.row.showStates === 1" type="primary" size="small" round @click.native.prevent="finishHandle(slotProps.row)">取消展示</el-button>-->
      <!--      </template>-->
      <template slot="outHandle">
        <el-col :span="3">
          <el-button type="primary" @click="handleAdd()"><i class="el-icon-plus" />添加</el-button>
        </el-col>
      </template>
      <template v-slot:handle="slotProps">
        <el-button type="primary" size="small" round @click.native.prevent="editHandle(slotProps.row)">编辑</el-button>
      </template>
    </wise-crud>
    <el-dialog ref="drawer" :title="title" :visible.sync="drawer" destroy-on-close>
      <div v-if="drawer" class="draw-body">
        <div class="wise-form">
          <el-form ref="ruleForm" :model="object" :rules="rules" :validate-on-rule-change="false" label-width="130px"
            label-suffix=":">
            <!--            <el-form-item label="所属项目" prop="projectId">-->
            <!--              <el-select v-model="object.projectId" clearable filterable placeholder="请输入项目编号" @change="selectInfo2">-->
            <!--                <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->

            <el-form-item label="网关编号" prop="gatewayId">
              <el-select v-model="object.gatewayId" filterable clearable placeholder="请选择网关编号">
                <el-option v-for="item in gatewayList" :key="item.id" :label="item.gatewayCode" :value="item.id"
                  :disabled="item.disabled" />
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="网关类型" prop="gatewayType">
              <el-select v-model="object.gatewayType">
                <el-option
                  v-="(item,index) in gatewayTypeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item> -->

            <el-form-item label="所属设备" prop="hjEqId">
              <el-select v-model="object.hjEqId" filterable clearable placeholder="请选择设备" @change="changeHjEq">
                <el-option v-for="(item,index) in hjEquipmentList" :key="item.id" :label="item.name" :value="item.id"
                  :disabled="item.disabled" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import WiseCrud from '@/components/Crud/wiseCrud'
  import {
    postHandle
  } from '@/api'
  export default {
    name: 'GatewayEquipmentManage',
    components: {
      WiseCrud
    },
    data() {
      return {
        urls: {
          list: '/api/v1/welder-sbtx-second/gateway-equipment-comb/list',
          add: '/api/v1/welder-sbtx-second/gateway-equipment/create',
          show: '/api/v1/welder-sbtx-second/gateway-equipment-comb/show/',
          update: '/api/v1/welder-sbtx-second/gateway-equipment-comb/update/',
          delete: '/api/v1/welder-sbtx-second/gateway-equipment-comb/remove/'
        },
        handle: [''],
        fields: [{
            label: '序号',
            type: 'index',
            use: ['table']
          },
          // {
          //   label: '所属项目',
          //   prop: 'projectInfo',
          //   type: 'select',
          //   labelWidth: '130px',
          //   url: '/api/v1/welder-sbtx-second/project-info',
          //   labelKey: 'name',
          //   valueKey: 'id',
          //   objKeys: [
          //     {
          //       field: 'projectId',
          //       key: 'id'
          //     }
          //   ],
          //   rules: [
          //     { required: true, message: '请选择项目', trigger: 'change' }
          //   ],
          //   placeholder: '请选择项目',
          //   use: ['filters']
          // },
          // {
          //   label: '所属项目',
          //   prop: 'manage',
          //   type: 'render',
          //   labelWidth: '130px',
          //   tableRender: (h, row, index) => {
          //     return h('div', row.projectInfo ? row.projectInfo.name : '')
          //   },
          //   viewRender: (h, item, object) => {
          //     return h('div', object.projectInfo ? object.projectInfo.name : '')
          //   },
          //   use: ['table', 'view']
          // },
          {
            label: '网关编号',
            prop: 'gatewayCode',
            type: 'render',
            labelWidth: '130px',
            tableRender: (h, row, index) => {
              return h('div', row.gateway ? row.gateway.gatewayCode : '')
            },
            viewRender: (h, item, object) => {
              return h('div', object.gateway ? object.gateway.gatewayCode : '')
            },
            use: ['table', 'view', 'search']
          },
          // {
          //   label: '网关类型',
          //   prop: 'gatewayType',
          //   type: 'radio',
          //   dataDic: 'gatewayType',
          //   labelWidth: '130px',
          //   use: ['table', 'view', 'search']
          // },
          {
            label: '所属设备',
            prop: 'manage',
            type: 'render',
            labelWidth: '130px',
            tableRender: (h, row, index) => {
              return h(
                'div',
                row.hjEquipmentInfo ? row.hjEquipmentInfo.name : ''
              )
            },
            viewRender: (h, item, object) => {
              return h(
                'div',
                object.hjEquipmentInfo ? object.hjEquipmentInfo.name : ''
              )
            },
            use: ['table', 'view']
          },
          {
            label: '所属项目',
            prop: 'projectInfo.name',
            type: 'text',
            labelWidth: '130px',
            use: ['table', 'view']
          },
          {
            label: '操作',
            type: 'handle',
            use: ['table'],
            handle: ['view', 'delete'],
            tableWidth: 300
          }
        ],
        drawer: false,
        title: '新增',
        projectList: [],
        gatewayList: [],
        hjEquipmentList: [],
        object: {
          gatewayId: null,
          gatewayType: null,
          showStates: null,
          projectId: null,
          hjEqId: null
        },
        hjEqId: null,
        gatewayTypeList: require('@/components/Crud/data/dataDictionary')
          .gatewayType,
        rules: {
          projectId: [{
            required: true,
            message: '请选择项目',
            trigger: 'blur'
          }],
          gatewayId: [{
            required: true,
            message: '请选择网关编号',
            trigger: 'blur'
          }]
        }
      }
    },
    computed: {
      entSpaceId() {
        return this.$store.getters.entSpaceId
      },
      filters() {
        return [{
          field: 'entSpaceId',
          operator: 'EQUALS',
          value: this.$store.getters.entSpaceId
        }]
      }
    },
    mounted() {
      
    },

    methods: {

      //所属设备切换
      changeHjEq(val) {
        this.hjEqId = val
        let hjeqIndex = this.hjEquipmentList.findIndex(item => val == item.id)
        this.object.gatewayType = this.hjEquipmentList[hjeqIndex].typeCode
      },
      handleAdd() {
        this.title = '新增'
        this.remoteMethod2()
        this.getHjEquipmentList()
        this.object = {
          gatewayId: null,
          gatewayType: null,
          showStates: null,
          projectId: null,
          hjEqId: null,
          entSpaceId: this.entSpaceId
        }
 
        this.drawer = true
      },
      async editHandle(row) {
        await this.remoteMethod2()
        await this.getHjEquipmentList()
        this.title = '编辑'
        this.getObjectById(row.id)
        this.drawer = true
      },
      startHandle(row) {
        this.$confirm('大屏是否展示?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            row.showStates = 1
            this.updateStatus(row)
            this.$message({
              type: 'success',
              message: '大屏展示成功!'
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      finishHandle(row) {
        this.$confirm('是否取消大屏展示?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            row.showStates = 0
            this.updateStatus(row)
            this.$message({
              type: 'success',
              message: '取消展示成功!'
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      },
      updateStatus(obj) {
        postHandle(this.urls.update + obj.id, {
          d: {},
          obj
        }).then((response) => {
          this.object = response.result
        })
      },
      getObjectById(id) {
        postHandle(this.urls.show + id, {}).then((response) => {
          this.object = response.result
          let data = response.result
          if (this.gatewayList.findIndex(item => item.id == data.gateway.id) === -1) {
            this.gatewayList.push({
              id: data.gateway.id,
              gatewayCode: data.gateway.gatewayCode,
              disabled: true
            })
          }
          if (this.hjEquipmentList.findIndex(item => item.id == data.hjEquipmentInfo.id) === -1) {
            this.hjEquipmentList.push({
              id: data.hjEqId,
              name: data.hjEquipmentInfo.name,
              disabled: true
            })
          }

          // this.object.gatewayId = data.gateway.id
          // this.object.hjEqId = data.hjEqId
          // this.object = data
          // for (let key in data) {
          //   this.object[key] = data[key]
          // }
          // this.object.projectName = this.object.projectInfo.name
          // this.remoteMethod2(this.object.projectId)
        })
      },
      // selectInfo2(value) {
      //   this.object.gatewayId = null
      //   if (value) {
      //     this.projectList.find(item => item.id === value)
      //     this.remoteMethod2(value)
      //   } else {
      //     this.gatewayList = []
      //   }
      // },
      // remoteMethod(query) {
      //   let params = {
      //     d: {
      //       page: {
      //         ps: 9999,
      //         p: 1
      //       },
      //       retPage: false
      //     }
      //   }
      //   postHandle('/api/v1/welder-sbtx-second/project-info', params).then(res => {
      //     this.loading = false
      //     this.projectList = res.result
      //   })
      // },
      async remoteMethod2() {
        let params = {
          d: {
            filters: [{
              field: 'entSpaceId',
              operator: 'EQUALS',
              value: this.entSpaceId
            }],
            page: {
              ps: 9999,
              p: 1
            },
            retPage: false
          },
          obj: {
            noClass: true
          }
        }
        this.loading = true
        await postHandle('/api/v1/welder-sbtx-second/gateway-comb/list', params).then(
          (res) => {
            // postHandle('/api/v1/welder-sbtx-second/gateway-equipment-comb/create', params).then(res => {
            this.loading = false
            this.gatewayList = res.result
          }
        )
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url
            if (this.object.id) {
              url = this.urls.update + this.object.id
            } else {
              url = this.urls.add
            }

            postHandle(url, {
                obj: {
                  ...this.object,
                }
              })
              .then((response) => {
                this.$message('操作成功')
                this.drawer = false
                if (this.object.id) {
                  this.$refs['wise-crud'].handleSearch(0)
                } else {
                  this.$refs['wise-crud'].handleSearch(1)
                }
              })
              .catch((error) => {
                const data = error.response.data
                for (const key in data) {
                  this.$message.error(this.$t(key + '.' + data[key]))
                }
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
        this.object.projectName = null
      },
      async getHjEquipmentList() {
        let params = {
          d: {
            filters: [{
              field: 'entSpaceId',
              operator: 'EQUALS',
              value: this.entSpaceId
            }],
            page: {
              ps: 9999,
              p: 1
            },
            retPage: false
          },
          obj: {
            noClass: true
          }
        }
        this.loading = true
        await postHandle(
          '/api/v1/welder-sbtx-second/hj-equipment-info-comb/list',
          params
        ).then((res) => {
          this.loading = false
          this.hjEquipmentList = res.result
        })
      }
    }
  }
</script>

<style>
</style>